#!/bin/bash
[% c("var/set_default_env") -%]
distdir=/var/tmp/dist/binutils
[% IF c("var/linux") %]
  # Config options for hardening-wrapper
  export DEB_BUILD_HARDENING=1
  export DEB_BUILD_HARDENING_STACKPROTECTOR=1
  export DEB_BUILD_HARDENING_FORTIFY=1
  export DEB_BUILD_HARDENING_FORMAT=1
  export DEB_BUILD_HARDENING_PIE=1
[% END -%]
[% IF c("var/linux-next") %]
  # Config options for dpkg-buildflags, see man(1) dpkg-buildflags
  # and https://wiki.debian.org/Hardening#Using_Hardening_Options
  # `+all` currently expands to
  # `+format,+fortify,+stackprotectorstrong,+relro,+bindnow,+pie`
  export DEB_BUILD_OPTIONS=hardening=+all
[% END -%]
[% IF c("var/linux-x86_64") || c("var/linux-arm") || c("var/linux-arm64") %]
  # The libstdc++ shipped by default is non-PIC which breaks the binutils build
  # if we build with DEB_BUILD_HARDENING_PIE=1. We need to install a PIC one AND
  # make sure it gets used before the non-PIC one would.
  ln -s /usr/lib/gcc/x86_64-linux-gnu/4.7/libstdc++_pic.a libstdc++.a
  export LDFLAGS="-L$rootdir -lstdc++"
[% END %]
tar xf [% project %]-[% c("version") %].tar.xz
cd [% project %]-[% c("version") %]
[% IF c('var/windows') -%]
  # Needed for the hardening... The upstream ticket is:
  # https://sourceware.org/bugzilla/show_bug.cgi?id=17321
  patch -p1 < ../enable-reloc-section-ld.patch
[% END -%]
[% IF c('var/windows-x86_64') -%]
  patch -p1 < ../64bit-fixups.patch
[% END -%]
./configure --prefix=$distdir [% c('var/configure_opt') %]
[% IF c("var/linux-next") -%]
  eval "$(dpkg-buildflags --export=sh)" && make -j[% c("buildconf/num_procs") %]
[% ELSE -%]
  make -j[% c("buildconf/num_procs") %]
[% END -%]
make install

[% IF c("var/linux") && ! c("var/gcc-cross") %]
  # Make sure gold is used with the hardening wrapper for full RELRO, see #13031.
  cd $distdir/bin
  rm ld
  cp /usr/bin/hardened-ld ./
  mv ld.gold ld.gold.real
  ln -sf hardened-ld ld.gold
  ln -sf ld.gold ld
[% END %]

[% IF c("var/gcc-cross") && ! c("var/linux-next") && 0 %]
  # Make sure gold is used with the hardening wrapper for full RELRO, see #13031.
  # First do the filename-prefixed ones...
  cd $distdir/bin
  rm [% c('var/gcc_target') %]-ld
  cp /usr/bin/hardened-ld ./
  mv [% c('var/gcc_target') %]-ld.gold [% c('var/gcc_target') %]-ld.gold.real
  ln -sf hardened-ld [% c('var/gcc_target') %]-ld.gold
  ln -sf [% c('var/gcc_target') %]-ld.gold [% c('var/gcc_target') %]-ld
  # Then do the directory-prefixed ones...
  cd $distdir/[% c('var/gcc_target') %]/bin
  rm ld
  cp /usr/bin/hardened-ld ./
  mv ld.gold ld.gold.real
  ln -sf hardened-ld ld.gold
  ln -sf ld.gold ld
[% END %]

cd /var/tmp/dist
[% c('tar', {
        tar_src => [ project ],
        tar_args => '-czf ' _ dest_dir _ '/' _ c('filename'),
        }) %]

